package org.sklse.learningassistant.controller;

import org.sklse.learningassistant.bean.Mistake;
import org.sklse.learningassistant.bean.PointList;
import org.sklse.learningassistant.bean.ResultModel;
import org.sklse.learningassistant.repository.MistakeRepository;
import org.sklse.learningassistant.repository.PointListRepository;
import org.sklse.learningassistant.service.MistakeService;
import org.sklse.learningassistant.service.ImageService;

import javax.servlet.ServletException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


@RestController
@RequestMapping("mistake")
public class MistakeController {

    //获取全部试题
    @RequestMapping(value = "getAllMistakes")
    public List<Mistake> getAllMistakes(){
        return mistakeRepository.findAll();
    }

    //根据id查询
    @RequestMapping(value = "getMistakeById")
    public Mistake getMistakeById(@RequestParam(value = "mistakeId") String mistakeId){return mistakeRepository.findByMisId(mistakeId);}
    //获取全部知识点
    @RequestMapping(value = "getAllPoints")
    public List<PointList> getAllPoints(){
        return pointListRepository.findAll();
    }

    //根据时间排列试题
    @RequestMapping(value = "getAllMistakesByTime")
    public List<Mistake> getAllMistakesByTime(){
        Sort sort = new Sort(Sort.Direction.DESC,"editTime");
        List<Mistake> mistakeList = mistakeRepository.findAll(sort);
       /* for(Mistake mistake1 : mistakeList){
            System.out.println(mistake1.getMisId());
        }*/
        return mistakeList;
    }

    //刚刚修改的
    @Autowired
    private MistakeRepository mistakeRepository;

    @Autowired
    private MistakeService mistakeService;

    @Autowired
    private ImageService imageService;

    @Autowired
    private PointListRepository pointListRepository;


    @RequestMapping(value = "getMistakesByPoint")
    public List<Mistake> getMistakesByPoint(@RequestParam(value = "currentPoint") String currentPoint){
        System.out.println(currentPoint);
        List<Mistake> mistakeList = mistakeRepository.findByPoints(currentPoint);
        //Sort sort = new Sort(Sort.Direction.DESC,"editTime");
       // List<Mistake> mistakeList2 = mistakeList.sort(,"editTime");
       // List<Mistake> mistakeList2 = (sort);
        ListSort(mistakeList);
        return mistakeList;
    }

    //按照editTime进行排序
    public static void ListSort(List<Mistake> mistakeList){
        Collections.sort(mistakeList, (mistake1, mistake2) -> {
            String editTime1 = mistake1.getEditTime();
            String editTime2 = mistake2.getEditTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                if (sdf.parse(editTime1).getTime() > sdf.parse(editTime2).getTime()) {
                    return 1;
                } else if (editTime1.equals(editTime2)) {
                    return 0;
                } else {
                    return -1;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0;
        });

    }

    @RequestMapping(value = "getMistakesByReason")
    public List<Mistake> getMistakesByReason(@RequestParam(value = "currentReason") String currentReason){
        System.out.println(currentReason);
        List<Mistake> mistakeList = mistakeRepository.findByReason(currentReason);
        return mistakeList;
    }


    @RequestMapping("find")
    public Mistake findById(@RequestParam(value = "id") String id){
        System.out.println(id);
        System.out.println(mistakeService.findById(id).getAnswPicUrl());
        return mistakeService.findById(id);
    }
//    @RequestMapping("upload")
//    public void upload(@RequestParam(value = "imgStr") String imgStr) throws IOException {
//        System.out.println(imgStr);
//        InputStream input=new FileInputStream(imgStr);
//        byte[] data= new byte[input.available()];
//        input.read(data);
//        input.close();
//        BASE64Encoder encoder = new BASE64Encoder();
//        Mistake error=new Mistake();
//        error.setSource("aaabbb");
//        error.setPoints("解析几何");
//        errorService.save(imgStr,error);
//        errorService.save(encoder.encode(data),error);
//
//    }


    /**
     * 提交保存错题
     * @param mistake
     */
    @RequestMapping(value = "/saveMistakes",method = RequestMethod.POST)
    public ResponseEntity<ResultModel> submitMistakes(Mistake mistake)throws ServletException {
        if(mistake.getMisId() == null){
            mistake.setMisId("12415");
            //return new ResponseEntity<>(ResultModel.error(HttpStatus.NOT_FOUND, "Get mistake_id error"), HttpStatus.NOT_FOUND);
        }else if(mistake.getPoints() == null){
            System.out.println("The point is null");
            return new ResponseEntity<>(ResultModel.error(HttpStatus.NOT_FOUND, "Get points error"), HttpStatus.NOT_FOUND);
        }else if(mistake.getQuesPicUrl() == null){
            return new ResponseEntity<>(ResultModel.error(HttpStatus.NOT_FOUND, "Get questionPicUrl error"), HttpStatus.NOT_FOUND);
        }

        PointList pointList = pointListRepository.findByPointName(mistake.getPoints());
        if(pointList != null){
            pointList.setCount((pointList.getCount()+1));
        }else {
            PointList pointList1 = new PointList();
            String pointName = mistake.getPoints();
            pointList1.setPointName(pointName);
            pointList1.setCount(1);
            pointListRepository.save(pointList1);
        }


        String quesPicUrl = imageService.convertToImage(mistake.getQuesPicUrl(),"quesPic555");
        System.out.println("quesPicUrl From Qiniu:"+quesPicUrl);
        String answerPicUrl = imageService.convertToImage(mistake.getAnswPicUrl(),"answerPic555");
        System.out.println("answerPicUrl From Qiniu:"+answerPicUrl);

        mistake.setQuesPicUrl(quesPicUrl);
        mistake.setAnswPicUrl(answerPicUrl);

        mistakeRepository.save(mistake);
        return new ResponseEntity<>(ResultModel.ok(HttpStatus.OK,mistake), HttpStatus.OK);

    }


    @RequestMapping(value = "convertToImg",method = RequestMethod.POST)
    public  ResponseEntity<ResultModel> convertToImg(String picUrl){
        System.out.println(picUrl);
        if(picUrl== null){
            return new ResponseEntity<>(ResultModel.error(HttpStatus.NOT_FOUND, "Get image error"), HttpStatus.NOT_FOUND);
        }
        // imageService.uploadImage(mistake.getQuesPicUrl(),"mistake"+mistake.getMisId());
        imageService.convertToImage(picUrl,"I:/ionic projects/sklse-LearningAssistant-master_2/LearningAssistant/src/main/resources/img/");
        return new ResponseEntity<>(ResultModel.ok(HttpStatus.OK,picUrl), HttpStatus.OK);
    }

    @RequestMapping(value = "/uploadImages",method = RequestMethod.POST)
    public  ResponseEntity<ResultModel> uploadImages(String picUrl){
        System.out.println("picUrl "+picUrl);
        if(picUrl== null){
            return new ResponseEntity<>(ResultModel.error(HttpStatus.NOT_FOUND, "Get image error"), HttpStatus.NOT_FOUND);
        }
        // imageService.uploadImage(mistake.getQuesPicUrl(),"mistake"+mistake.getMisId());
        for(int i = 0; i < picUrl.length(); i++){
            if(picUrl.charAt(i) == ' '){
                picUrl.replace(picUrl.charAt(i),'+');
            }
        }
        imageService.uploadImage(picUrl,"test111");
        return new ResponseEntity<>(ResultModel.ok(HttpStatus.OK,picUrl), HttpStatus.OK);
    }

    @RequestMapping(value = "savePicture",method = RequestMethod.POST)
    public  ResponseEntity<ResultModel> savePicture(@RequestParam("request") MultipartHttpServletRequest request){
        if(request == null){
            return new ResponseEntity<>(ResultModel.error(HttpStatus.NOT_FOUND, "Get image error"), HttpStatus.NOT_FOUND);
        }
        imageService.savePicture(request);

        return new ResponseEntity<>(ResultModel.ok(HttpStatus.OK,request), HttpStatus.OK);
    }


    /**
     * 提交保存错题
     * @param mistake
     */
    @RequestMapping("save")
    public void save( @RequestBody Mistake mistake){

        mistakeService.save(mistake);
    }

//    @RequestMapping("upload")
//    public void upload(@RequestParam(value = "imgStr") String imgStr){
//          System.out.println(imgStr);
//          Mistake error=new Mistake();
//          error.setSource("aaabbb");
//          error.setPoints("解析几何");
//          errorService.save(imgStr,error);
//    }
    @RequestMapping("hello")
    public String Hello(){
        return "success";
    }
}
